package top.byfree.jbyan.saber.config

import cn.dev33.satoken.interceptor.SaInterceptor
import cn.dev33.satoken.stp.StpUtil
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

/**
 * 全局web配置
 *
 * @author jbyan
 * @since 21/3/2024
 */
@Configuration
open class WebConfig : WebMvcConfigurer {

    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(SaInterceptor { StpUtil.checkLogin() })
            .addPathPatterns("/**")
            .excludePathPatterns("/auth/*")

        registry.addInterceptor(SaInterceptor())
            .addPathPatterns("/**")
    }

    /* 跨域配置 */
    @Bean
    open fun corsFilter(): CorsFilter {
        val corsConfiguration = CorsConfiguration()
        //1.允许任何来源
        corsConfiguration.setAllowedOriginPatterns(listOf("*"))
        //2.允许任何请求头
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL)
        //3.允许任何方法
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL)
        //4.允许凭证
        corsConfiguration.allowCredentials = true
        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", corsConfiguration)
        return CorsFilter(source)
    }
}